<template>
  <div class="edit-user-box">
    <el-form ref="form" :model="formData" :rules="rules" label-width="80px">
      <template v-for="item in formList">
        <el-form-item
          :key="item.prop"
          :label="item.name"
          :prop="item.prop"
          :class="item.itemClass"
        >
          <component
            :is="item.componentType || 'el-input'"
            v-model="formData[item.prop]"
            :pop-data="formData"
            :prop-key="item.prop"
            :clearable="true"
            v-bind="item.attrConfig || {}"
            v-on="item.listenersConfig"
            @change="handlerSelectData(item)"
            @changeImg="changeImg"
          >
            <template v-for="option in item.optionList">
              <el-option
                :key="option.code"
                :label="option.name"
                :value="option.code"
              />
            </template>
          </component>
        </el-form-item>
      </template>
    </el-form>
  </div>
</template>

<script>
import { arr2tree } from '@/utils'
import AddImg from '@/components/PopItems/add-img'

export default {
  name: 'EditUser',
  components: { AddImg },
  props: {
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        fullName: null,
        deptId: null,
        postIds: null,
        post: null,
        mobilePhone: null,
        email: null,
        address: null,
        remark: null,
        avatarUrl: ''
      },
      formList: [
        {
          name: '姓名',
          prop: 'fullName',
          attrConfig: { placeholder: '请输入姓名', maxlength: 64 }
        },
        {
          name: '头像',
          prop: 'avatarUrl',
          componentType: 'AddImg',
          itemClass: 'width100p',
          attrConfig: { placeholder: '请上传头像' }
        },
        {
          name: '所属机构',
          prop: 'deptId',
          componentType: 'el-cascader',
          attrConfig: {
            placeholder: '请选择所属机构',
            'show-all-levels': false,
            'collapse-tags': true,
            props: {
              checkStrictly: true,
              multiple: false,
              emitPath: false,
              children: 'children',
              label: 'deptName',
              value: 'id'
            },
            options: []
          },
          optionList: [],
          selectPath: 'deptTree',
          selectParams: {},
          dataProp: {
            dataType: 'resData',
            nameProp: 'deptName',
            codeProp: 'id',
            treeConfig: {
              id: 'id',
              parentId: 'parentId',
              childrenKey: 'children'
            }
          }
        },
        {
          name: '岗位',
          prop: 'postIds',
          componentType: 'el-select',
          optionList: [],
          selectPath: 'selectedList',
          selectParams: {
            codeList: ['PostSelected']
          },
          attrConfig: {
            placeholder: '请选择岗位',
            'collapse-tags': true,
            multiple: true,
            options: []
          },
          dataProp: {
            keyProp: 'PostSelected',
            nameProp: 'label',
            codeProp: 'value'
          },
          selectStyle: { width: '180px' }
        },
        {
          name: '手机号码',
          prop: 'mobilePhone',
          attrConfig: { placeholder: '请输入手机号码' }
        },
        {
          name: '邮箱',
          prop: 'email',
          attrConfig: { placeholder: '请输入邮箱' }
        },
        {
          name: '联系地址',
          prop: 'address',
          itemClass: 'width100p',
          attrConfig: { placeholder: '请输入联系地址', maxlength: 500 }
        },
        {
          name: '备注',
          prop: 'remark',
          itemClass: 'width100p',
          attrConfig: {
            type: 'textarea',
            placeholder: '请输入备注信息'
          }
        }
      ]
    }
  },
  computed: {
    rules() {
      return {
        fullName: [
          { required: true, message: '请输入姓名', trigger: 'blur' },
          { required: true, message: '姓名长度过长', max: 24, trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '请选择所属机构', trigger: 'change' }
        ],
        mobilePhone: [
          {
            required: false,
            trigger: 'blur',
            validator: this.mobilePhoneValidate
          }
        ],
        email: [
          { required: false, trigger: 'blur', validator: this.emailValidate }
        ]
      }
    }
  },
  watch: {
    popData: {
      handler(data) {
        if (data) {
          this.formList.forEach((e) => {
            this.$set(this.formData, e.prop, data[e.prop])
          })
        }
      },
      deep: true,
      immediate: true
    },
    confirm() {
      const { deptId } = this.formData
      let deptIdVal = deptId
      if (Object.prototype.toString.call(deptId) === '[object Array]') {
        deptIdVal = deptId[deptId.length - 1]
      }
      const params = {
        ...(this.formData || {}),
        deptId: deptIdVal || '',
        id: this.popData.id
      }
      this.submit(params)
    }
  },
  created() {
    this.formList.forEach((e) => {
      if (e.selectPath) {
        this.getSelectData(e)
      }
    })
  },
  methods: {
    /**
     * 获取筛选数据
     */
    getSelectData(item) {
      const { selectPath, selectParams, dataProp, prop } = item || {}
      const params = {
        ...(selectParams || {})
      }
      const newPath = selectPath.split('.')
      let api = this.$api
      newPath.forEach((e) => {
        api = api[e]
      })
      api(params).then((res) => {
        if (Number(res.code) === 1000 && res.data) {
          if (dataProp) {
            const { dataType, treeConfig, keyProp, nameProp, codeProp } =
              dataProp
            const selectList =
              dataType === 'resData' ? res.data || [] : res.data[keyProp] || []

            let optionList = treeConfig
              ? arr2tree(selectList, treeConfig)
              : selectList.map((e) => ({
                ...e,
                name: e[nameProp],
                code: e[codeProp]
              }))

            if (prop === 'deptId') {
              optionList = optionList.filter((e) => e.id !== '001') || []
            }
            if (item.componentType === 'el-cascader') {
              this.$set(item.attrConfig, 'options', optionList)
            } else {
              this.$set(item, 'optionList', optionList)
            }
          }
        }
      })
    },
    /**
     * 提交
     */
    submit(params) {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          // 上传新头像
          if (typeof this.formData.avatarUrl !== 'string' && this.formData.avatarUrl) {
            const formData = new FormData()
            formData.append('file', this.formData.avatarUrl.raw)
            const urlRes = await this.$api.fileManage.baseUploadData(
              '/energy-carbon/grass-file/file/upload',
              formData
            )
            if (Number(urlRes.code) === 1000) {
              this.formData.avatarUrl = urlRes.data
              params.avatarUrl = urlRes.data
            }
          }
          const res = await this.$api.userManage.update(params)
          if (Number(res.code) === 1000) {
            this.$message.success('修改成功!')
            this.$emit('onFinish', 'edit-user')
          }
        }
      })
    },
    // 上传律师头像
    changeImg(key, value) {
      this.$set(this.formData, 'avatarUrl', value)
    },
    /**
     * 验证用户名
     */
    userNameValidate(rule, value, callback) {
      // 4到16位（字母，数字，下划线，减号）
      // const REP = new RegExp(/^[a-zA-Z0-9_-]{4,16}$/)
      // 4到16位（字母，数字）
      const REP = new RegExp(/^[a-zA-Z0-9_-]{1,}$/)
      if (!REP.test(value)) {
        callback(new Error('您的用户名格式有误!'))
      } else {
        callback()
      }
    },
    /**
     * 验证手机号
     */
    mobilePhoneValidate(rule, value, callback) {
      const REP = new RegExp(/^1[3456789]\d{9}$/)
      if (value && !REP.test(value)) {
        callback(new Error('请输入正确的手机号码!'))
      } else {
        callback()
      }
    },
    /**
     * 验证邮箱
     */
    emailValidate(rule, value, callback) {
      const REP = new RegExp(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/)
      if (value && !REP.test(value)) {
        callback(new Error('请输入正确的邮箱格式!'))
      } else {
        callback()
      }
    },
    /**
     * change事件
     */
    handlerSelectData(config) {
      const Ref = this.$refs[config.prop]
      if (Ref && config.isClosePop) {
        Ref.dropDownVisible = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.edit-user-box {
  color: #333;
  padding: 0 20px;

  .el-form {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    .el-form-item {
      width: calc(50% - 10px);

      &.width100p {
        width: 100%;
      }
    }

    .el-select,
    .el-cascader {
      width: 100%;
    }
  }
}
</style>
